from src.tools.dep import *
from src.tools.config import Config
from src.tools.utils import nodetemp
from src.tools.permission import checker
from src.tools.file import read, write
import json
import sys
import nonebot

from nonebot import on_command
from nonebot.adapters import Message
from nonebot.adapters.onebot.v11 import Bot, Event, GroupMessageEvent
from nonebot.params import CommandArg


block = on_command("block", aliases={"加黑", "避雷"}, priority=5)  # 综合避雷名单-添加


@block.handle()
async def _(bot: Bot, event: Event, args: Message = CommandArg()):
    arg = args.extract_plain_text().split(" ")
    personal_data = await bot.call_api("get_group_member_info", group_id=event.group_id, user_id=event.user_id, no_cache=True)
    group_admin = personal_data["role"] in ["owner", "admin"]
    
    x = Permission(event.user_id).judge(5, '添加避雷')
    if not x.success and not group_admin:
        return await block.finish("唔……只有群主或管理员才能修改哦~")
    if len(arg) != 2:
        return await block.finish("唔……需要2个参数，第一个参数为玩家名，第二个参数是原因~\n提示：理由中请勿包含空格。")
    sb = arg[0]
    reason = arg[1]
    new = {"ban": sb, "reason": reason}
    now = json.loads(read(bot_path.DATA + "/" + str(event.group_id) + "/blacklist.json"))
    for i in now:
        if i["ban"] == sb:
            return await block.finish("该玩家已加入黑名单。")
    now.append(new)
    write(bot_path.DATA + "/" + str(event.group_id) + "/blacklist.json", json.dumps(now, ensure_ascii=False))
    return await block.finish("成功将该玩家加入黑名单！")

unblock = on_command("unblock", aliases={"删黑"}, priority=5)  # 解除避雷


@unblock.handle()
async def _(bot: Bot, event: Event, args: Message = CommandArg()):
    arg = args.extract_plain_text().split(" ")
    personal_data = await bot.call_api("get_group_member_info", group_id=event.group_id, user_id=event.user_id, no_cache=True)
    group_admin = personal_data["role"] in ["owner", "admin"]
    
    x = Permission(event.user_id).judge(5, '移除避雷')
    if not x.success and not group_admin:
        return await block.finish("唔……只有群主或管理员才能修改哦~")
    if len(arg) != 1:
        return await unblock.finish("参数仅为玩家名，请勿附带任何信息！")
    sb = arg[0]
    now = json.loads(read(bot_path.DATA + "/" + str(event.group_id) + "/blacklist.json"))
    for i in now:
        if i["ban"] == sb:
            now.remove(i)
            write(bot_path.DATA + "/" + str(event.group_id) + "/blacklist.json",
                  json.dumps(now, ensure_ascii=False))
            return await unblock.finish("成功移除该玩家的避雷！")
    return await unblock.finish("移除失败！尚未避雷该玩家！")

sblock = on_command("sblock", aliases={"查黑"}, priority=5)  # 查询是否在避雷名单


@sblock.handle()
async def _(event: Event, args: Message = CommandArg()):
    arg = args.extract_plain_text().split(" ")
    if len(arg) != 1:
        return await sblock.finish("参数仅为玩家名，请勿附带任何信息！")
    sb = arg[0]
    now = json.loads(read(bot_path.DATA + "/" + str(event.group_id) + "/blacklist.json"))
    for i in now:
        if i["ban"] == sb:
            reason = i["reason"]
            msg = f"玩家[{sb}]被避雷的原因为：\n{reason}"
            return await sblock.finish(msg)
    return await sblock.finish("该玩家尚未被避雷哦~")

lblock = on_command("lblock", aliases={"列黑"}, priority=5)  # 列出所有黑名单


@lblock.handle()
async def _(bot: Bot, event: GroupMessageEvent):
    now = json.loads(read(bot_path.DATA + "/" + str(event.group_id) + "/blacklist.json"))
    f = ""
    for i in now:
        pl = i["ban"]
        r = i["reason"]
        p = f"玩家名：{pl}\n避雷原因：{r}\n"
        f = f + "\n" + p
    f = f[1:]
    node = nodetemp("避雷查询", Config.bot[0], f)
    await bot.call_api("send_group_forward_msg", group_id=event.group_id, messages=node)
